package com.example.demo.controller;

import com.example.demo.pojo.Comment;
import com.example.demo.pojo.User;
import com.example.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
@Controller
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/submit")
    public String submitComment(@RequestParam String content, HttpSession session, Model model) {
        // 从 session 中获取 currentUser 对象
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login"; // 如果用户未登录，重定向到登录页面
        }

        // 获取用户名
        String username = currentUser.getNickname();

        // 保存评论
        commentService.saveComment(username, content);
        return "redirect:/comments"; // 提交后重定向到评论列表页面
    }

    // 分页展示评论
    @GetMapping
    public String getComments(@RequestParam(defaultValue = "0") int page, Model model) {
        int pageSize = 10; // 每页显示 10 条评论
        Page<Comment> commentPage = commentService.getComments(PageRequest.of(page, pageSize));

        model.addAttribute("comments", commentPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", commentPage.getTotalPages());
        System.out.println("评论提交成功！ ");
        return "comment-list"; // 返回评论列表页面
    }
}